import pymysql
import json
import os

BASEURL = 'http://192.168.121.18'
WEIBO_DIR = '/home/sin/weibo/weibo'
MYSQL_HOST = 'localhost'
MYSQL_USER = 'sin'
MYSQL_PASSWORD = '123456'
MYSQL_DB = 'weibo'

caches = {}
for root, dirs, files in os.walk(WEIBO_DIR):
    for file in files:
        file_path = os.path.join(root, file)
        id = file[9:18]
        if id not in caches:
            caches[id] = {'images': [], 'videos': [], 'type': ''}
        if file.endswith("mp4"):
            caches[id]['type'] = 'video'
            caches[id]['videos'].append((BASEURL + file_path[len(WEIBO_DIR):]))
        elif file.endswith("jpg") or file.endswith("gif"):
            caches[id]['type'] = 'image'
            caches[id]['images'].append({'src': BASEURL + file_path[len(WEIBO_DIR):]})
        else:
            raise Exception("有不认识的格式" + file)

threads = []

conn = pymysql.connect(host=MYSQL_HOST, user=MYSQL_USER, password=MYSQL_PASSWORD, database=MYSQL_DB)
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute(
    "select weibo.id, weibo.content, weibo.original_pictures, weibo.video_url, weibo.publish_time, user.nickname from weibo left join user on weibo.user_id = user.id order by publish_time desc")

for _thread in cur.fetchall():
    id = _thread.get('id')
    nickname = _thread.get('nickname')
    if id in caches:
        _thread.update(caches[id])
        threads.append(_thread)

print(json.dumps({"data": threads}, default=str))
cur.close()
conn.close()